package com.yoda.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yoda.constant.MessageConstant;
import com.yoda.constant.StatusConstant;
import com.yoda.context.BaseContext;
import com.yoda.dto.EmployeeLoginDto;
import com.yoda.dto.UserDto;
import com.yoda.dto.UserPageQuery;
import com.yoda.entity.*;
import com.yoda.mapper.*;
import com.yoda.result.Result;
import com.yoda.service.ISysUserService;
import com.yoda.utils.JwtUtil;
import com.yoda.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-05-15
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysDictMapper sysDictMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private YddCateMapper yddCateMapper;

    @Autowired
    private YddAdvposMapper yddAdvposMapper;

    @Autowired
    private YddTagMapper yddTagMapper;

    @Autowired
    private YddUserMapper yddUserMapper;

    @Autowired
    private YddArticleMapper yddArticleMapper;

    @Autowired
    private YddAdvimgMapper yddAdvimgMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private UsersVoMapper usersVoMapper;


    /**
     * 登入
     * @param dto
     * @return
     */
    @Override
    public Result login(EmployeeLoginDto dto) {
        String username = dto.getLoginName();
        String password = dto.getPassword();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        QueryWrapper<SysUser> qw = new QueryWrapper();
        qw.lambda().eq(SysUser::getLoginName,username);
        SysUser sysUser = getOne(qw);

        if (sysUser == null) {
            //账号不存在
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!pwd.equals(sysUser.getPassword())) {
            //密码错误
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }

        if (sysUser.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            return Result.error(MessageConstant.ACCOUNT_LOCKED);
        }
        String token = JwtUtil.getToken(Long.valueOf(sysUser.getId()));

        SysUserVo vo = SysUserVo.builder()
                .token(token)
                .build();

        return Result.success(vo);
    }

    /**
     * 获取用户资料
     * @return
     */
    @Override
    public Result profile() {
        UserInfoVo vo = new UserInfoVo();
        vo.setBtnList("*");
        Long currentId = BaseContext.getCurrentId();
        SysUser sysUser = getById(currentId);
        //封装UserList

        List<SysInfoVo> userList = new ArrayList();
        SysInfoVo sysInfoVo = new SysInfoVo();
        BeanUtils.copyProperties(sysUser,sysInfoVo);



        //根据roleId查询出关联角色菜单表
        String roleId = sysUser.getRoleId().substring(2,sysUser.getRoleId().length()-2);
        String name = sysRoleMapper.selectById(roleId).getName();
        sysInfoVo.setRoleName(new String[]{name});
        vo.setUserInfo(sysInfoVo);
        LambdaQueryWrapper<SysRoleMenu> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(SysRoleMenu::getRoleId,roleId);
        lambdaQuery.select(SysRoleMenu::getMenuId);
        List<SysRoleMenu> menuList = sysRoleMenuMapper.selectList(lambdaQuery);
        //通过查询出的menuId查询菜单表的数据并插入
        LambdaQueryWrapper<SysMenu> menuqw = Wrappers.lambdaQuery();
        menuList.stream().forEach(menu->{
            menuqw.in(SysMenu::getType,"1");
        });
        List<SysMenu> sysMenus = sysMenuMapper.selectList(menuqw);
        vo.setMenuList(sysMenus);

        //"dictsList"查询赋值

        DictsVo dictsVo = new DictsVo();
        dictsVo.setTheme(getDict("theme"));
        dictsVo.setTableType(getDict("table_type"));
        dictsVo.setInterfaceType(getDict("interface_type"));
        dictsVo.setOrderType(getDict("order_type"));
        dictsVo.setReportType(getDict("report_type"));
        vo.setDictsList(dictsVo);


        return Result.success(vo);
    }

    /**
     * 主页统计信息
     * @return
     */
    @Override
    public Result baseInfo() {
        SysTotalVo vo = new SysTotalVo();
        List<YddCateVo> allCate = new ArrayList<>();
        List<YddCate> yddCateList = yddCateMapper.selectList(null);
        yddCateList.stream().forEach(yddCate -> {
            YddCateVo cateVo = new YddCateVo();
            cateVo.setId(yddCate.getId());
            cateVo.setCatename(yddCate.getCatename());
            cateVo.setNum(yddCate.getSortNum());
            allCate.add(cateVo);
        });
        vo.setAllCate(allCate);
        vo.setAdvposNum(yddAdvposMapper.selectCount(null).intValue());
        vo.setTagNum(yddTagMapper.selectCount(null).intValue());
        long l = this.count();
        vo.setAdminNum(Integer.valueOf(l+""));
        vo.setArticleNum(yddArticleMapper.selectCount(null).intValue());
        vo.setCateNum(yddCateMapper.selectCount(null).intValue());
        vo.setAdvimgNum(yddAdvimgMapper.selectCount(null).intValue());
        YddUserVo userVo = new YddUserVo();
        //获取男性
        LambdaQueryWrapper<YddUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(YddUser::getSex,"0");
        Long man = yddUserMapper.selectCount(lambdaQuery);
        //获取女性
        LambdaQueryWrapper<YddUser> lambdaQuery2 = Wrappers.lambdaQuery();
        lambdaQuery2.eq(YddUser::getSex,"1");
        Long woman = yddUserMapper.selectCount(lambdaQuery2);
        userVo.setUserMan(man.intValue());
        userVo.setUserWoman(woman.intValue());
        userVo.setTotal(man.intValue()+woman.intValue());
        vo.setUser(userVo);

        LambdaQueryWrapper<YddUser> wrapper = Wrappers.lambdaQuery();
        wrapper.likeRight(YddUser::getUsername,"1");
        List<YddUser> yddUserList = yddUserMapper.selectList(wrapper);
        vo.setNewUser(yddUserList);

        List<YddArticle> yddArticleList = yddArticleMapper.selectList(null);
        vo.setHotArticle(yddArticleList);


        return Result.success(vo);
    }

    private Map getDict(String str){
        LambdaQueryWrapper<SysDict> dictTheme = Wrappers.lambdaQuery();
        dictTheme.eq(SysDict::getType,str);
        List<SysDict> dictList = sysDictMapper.selectList(dictTheme);
        Map map = new HashMap();
        dictList.stream().forEach(sysDict -> {
            String value = sysDict.getValue();
            String label = sysDict.getLabel();
            map.put(value,label);
        });
        return map;
    }



    /**
     * 用户列表-分页
     * @param query
     * @return
     */
    @Override
    public Result userPageQuery(UserPageQuery query) {
        //非空判断
        if (query.getPage() == 0){
            query.setPage(1);
        }
        if (query.getLimit() == 0){
            query.setLimit(10);
        }
        //开始分页
        IPage<SysUser> iPage = new Page<>(query.getPage(),query.getLimit());
        //开启条件查询
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        if (query.getLoginName() != null && query.getLoginName() != "" ){
            wrapper.like(SysUser::getLoginName,query.getLoginName());
        }
        if (query.getPhone() != null && query.getPhone() != ""){
            wrapper.like(SysUser::getPhone,query.getPhone());
        }
        if (query.getStatus() != null && query.getStatus() != ""){
            wrapper.like(SysUser::getStatus,query.getStatus());
        }
        this.page(iPage,wrapper);
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);

        List<UsersVo> list = new ArrayList<>();
        List<SysUser> records = iPage.getRecords();
        for (SysUser record : records) {
            UsersVo vo = new UsersVo();
            BeanUtils.copyProperties(record,vo);
            List<String> roleName = new ArrayList<>();
            List<String> roleId = JSON.parseArray(record.getRoleId(), String.class);
            for (String s : roleId) {
                SysRole sysRole = sysRoleMapper.selectById(s);
                roleName.add(sysRole.getName());
            }
            vo.setRolename(roleName);
            list.add(vo);
        }

        sysUserMapper.selectPage(iPage,wrapper);

        UserVo vo = new UserVo();
        vo.setTotalPages((int) iPage.getPages());
        vo.setPageSize((int) iPage.getSize());
        vo.setCurrentPage((int) iPage.getCurrent());
        vo.setCount((int) iPage.getTotal());
        vo.setData(list);
        return Result.success(vo);
    }

    /**
     * 根据id进行管理员删除
     * @param id
     * @return
     */
    @Override
    public Result deleteById(String id) {
        //判断非空
        if (id == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //开启条件
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUser::getId,id);
        //根据条件删除
        this.remove(wrapper);
        return Result.success();
    }

    /**
     * 管理员添加
     * @param dto
     * @return
     */
    @Override
    public Result addUser(UserDto dto) {
        //新建对象，复制之后返回
        SysUser sysUser = new SysUser();
        System.out.println(dto.getLogin_name());
        sysUser.setCreateDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());

        List<String> roleId = dto.getRoleId();
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < roleId.size(); i++) {
            if (i == roleId.size()-1){
                sb.append('"').append(roleId.get(i)).append('"').append("]");
            }else {
                sb.append('"').append(roleId.get(i)).append('"').append(",");
            }
        }
        sysUser.setRoleId(sb.toString());
        sysUser.setStatus(dto.getStatus());
        sysUser.setLoginName(dto.getLogin_name());
        BeanUtils.copyProperties(dto,sysUser);
        this.save(sysUser);
        //返回成功
        return Result.success();
    }

    /**
     * 管理员修改
     * @param dto
     * @return
     */
    @Override
    public Result updateUser(UserDto dto) {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUser::getId,dto.getId());
        SysUser user = sysUserMapper.selectOne(wrapper);
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(dto.getLogin_name());
        BeanUtils.copyProperties(user,sysUser);
        BeanUtils.copyProperties(dto,sysUser);
        sysUser.setStatus(dto.getStatus());
        if (dto.getRoleId() != null && dto.getRoleId().size() != 0 ) {
            List<String> id = dto.getRoleId();
            StringBuilder sb = null;
            sb = new StringBuilder("[");
            for (int i = 0; i < id.size(); i++) {
                if (i == id.size()-1){
                    sb.append('"').append(id.get(i)).append('"').append("]");
                }else {
                    sb.append('"').append(id.get(i)).append('"').append(",");
                }
            }
            String s = sb.toString();
            sysUser.setRoleId(s);
        }
        this.update(sysUser,wrapper);
        return Result.success();
    }

    /**
     * 根据id获取角色详情
     * @param id
     * @return
     */
    @Override
    public Result rowInfo(String id) {
        //根据id获取到用户的所有信息
        SysUser user = getById(id);
        UsersVo vo = new UsersVo();
        String roleId = user.getRoleId();
        List<String> list = new ArrayList<>();
        String[] split = roleId.split("\"");
        for (int i = 1; i < split.length; i += 2) {
            list.add(split[i]);
        }
        vo.setRole_id(list);
        BeanUtils.copyProperties(user,vo);
        return Result.success(vo);
    }

}
